package com.nowcoder.community.controller;

import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.kafka.EventProducer;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class FollowController implements ResponseCode, CommunityConstant {

    @Autowired
    private FollowService followService;

    @Autowired
    private UserService userService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private HostHolder hostHolder;

    /**
     * 异步请求
     * @return
     */
    @RequestMapping(path = "/follow", method = RequestMethod.POST)
    @ResponseBody
    public String follow(int entityType, int entityId) {
        User user = hostHolder.getUsers();
        if(user == null) {
            return CommunityUtil.getJsonString(USER_UNLOGIN_CODE, "尚未登陆!请先登陆");
        }
        followService.follow(user.getId(), entityType, entityId);

        Event event = new Event();
        event.setTopic(TOPIC_FOLLOW)
                .setUserId(user.getId())
                .setEntityId(entityId)
                .setEntityType(entityType)
                .setEntityUserId(entityId)
                // 关注我的人(粉丝)
                // 通过这个id链接到该粉丝的个人主页
                .setData("targetUserId", user.getId());
        eventProducer.fireEvent(event);

        return CommunityUtil.getJsonString(SUCCESS_CODE, "已关注!");
    }

    @RequestMapping(path = "/unfollow", method = RequestMethod.POST)
    @ResponseBody
    public String unfollow(int entityType, int entityId) {
        User user = hostHolder.getUsers();
        if(user == null) {
            return CommunityUtil.getJsonString(USER_UNLOGIN_CODE, "尚未登陆!请先登陆");
        }
        followService.unfollow(user.getId(), entityType, entityId);
        return CommunityUtil.getJsonString(SUCCESS_CODE, "已取消关注!");
    }

    private boolean hasFollowed(int targetUserId) {
        // 当前执行查询的用户
        User user = hostHolder.getUsers();
        if(user == null) {
            return false;
        }
        int currentUserId = user.getId();
        return followService.isFollowed(currentUserId, ENTITY_TYPE_USER, targetUserId);
    }

    @RequestMapping(path = "/followees/{userId}", method = RequestMethod.GET)
    public String getFollowees(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if(user == null) {
            throw new RuntimeException("目标用户不存在!");
        }
        page.setLimit(5);
        page.setRows((int)followService.findFolloweeCount(userId, ENTITY_TYPE_USER));
        page.setPath("/followees/" + userId);
        List<Map<String, Object>> followeeList = followService.findFolloweeList(userId, ENTITY_TYPE_USER, page.getLimit(), page.getOffSet());
        if(followeeList != null) {
            for(Map<String, Object> map : followeeList) {
                User u = (User) map.get("user");
                // 确认当前查询者对被查询者关注列表中
                // 各个用户的关注状态
                map.put("isFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("user", user);
        model.addAttribute("followees", followeeList);
        return "/site/followee";
    }

    @RequestMapping(path = "/followers/{userId}", method = RequestMethod.GET)
    public String getFollowers(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if(user == null) {
            throw new RuntimeException("目标用户不存在!");
        }
        page.setLimit(5);
        page.setRows((int)followService.findFollowerCount(ENTITY_TYPE_USER, userId));
        page.setPath("/followers/" + userId);
        List<Map<String, Object>> followerList = followService.findFollowerList(ENTITY_TYPE_USER, userId, page.getLimit(), page.getOffSet());
        if(followerList != null) {
            for(Map<String, Object> map : followerList) {
                User u = (User) map.get("user");
                // 确认当前查询者对被查询者关注列表中
                // 各个用户的关注状态
                map.put("isFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("user", user);
        model.addAttribute("followers", followerList);
        return "/site/follower";
    }

}
